<template>
	<xn-form-container :title="title" :width="700" :visible="visible" :destroy-on-close="true" @close="onClose">
		<component :is="currentForm" ref="flowFormRef" @onDraft="saveDraft" @onSubmit="subFlow" :record="formData" />
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button
				style="margin-right: 8px"
				type="primary"
				@click="onDraft"
				:submitLoading="submitLoading"
				v-if="!props.isPreview"
				>保存草稿</a-button
			>
			<a-button type="danger" @click="onSubmit" v-if="!props.isPreview">提交</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="componentForm">
	import { cloneDeep } from 'lodash-es'
	import sysFlowDraftApi from '@/api/flow/sysFlowDraftApi'
	// 抽屉状态
	const visible = ref(false)
	const props = defineProps({
		isPreview: {
			type: Boolean,
			default: true
		}
	})
	const emit = defineEmits({ successful: null })
	const submitLoading = ref(false)
	const currentForm = shallowRef()
	const title = ref('')
	const flowFormRef = ref()
	const formData = ref({
		dataJson: '',
		flowId: '',
		draftId: '',
		formRouter: ''
	})
	const { proxy } = getCurrentInstance()

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		title.value = record.formTitle
		formData.value.dataJson = record.dataJson ? JSON.parse(record.dataJson) : {}
		formData.value.flowId = record.flowId
		formData.value.draftId = record.id
		formData.value.formRouter = record.formRouter
		loadComponent(record.formRouter)
	}

	/**
	 * 动态组件
	 */
	const loadComponent = async (component) => {
		currentForm.value = await defineAsyncComponent(() => import(/* @vite-ignore */ `./component/${component}.vue`))
	}
	const onDraft = () => {
		proxy.$refs.flowFormRef.onOpen()
	}
	const onSubmit = () => {
		flowFormRef.value.onSubmit()
	}
	/**
	 * 保存草稿
	 */
	const saveDraft = (v) => {
		submitLoading.value = true
		let param = {
			flowId: formData.value.flowId,
			flowTitle: title.value,
			formJson: formData.value.formRouter
		}
		param.dataJson = JSON.stringify(v)
		sysFlowDraftApi
			.sysFlowDraftSubmitForm(param, false)
			.then(() => {
				emit('successful')
				onClose()
			})
			.finally(() => {
				submitLoading.value = false
			})
	}
	/**
	 * 提交流程
	 */
	const subFlow = (v) => {
		if (v.id) {
			let params = [
				{
					id: v.id
				}
			]
			sysFlowDraftApi.sysFlowDraftDelete(params).then(() => {
				emit('successful')
				onClose()
			})
		} else {
			onClose()
		}
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
